package com.heima.kafka.simple;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;

/**
 * 消费者
 */
public class ConsumerStart {
    public static void main(String[] args) {
        //2.设置配置
        Properties properties =new Properties();
        //连接kafka
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.35.135:9092");
        //对消息的进行反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        //消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");


        //改为手动提交
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");

        //1.创建消费者对象
        KafkaConsumer<String,String> kafkaConsumer = new KafkaConsumer<String, String>(properties);

        /**
         * 3.订阅消息主题
         */

        kafkaConsumer.subscribe(Collections.singletonList("simple_topic"));

        while (true){
            //4.拉取消息
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofMillis(10000));
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println("消息的key:"+ consumerRecord.key()+",消息的value"+consumerRecord.value()+",消息的偏移量:"+consumerRecord.offset());
                //同步提交偏移量
                kafkaConsumer.commitSync();
                //异步提交偏移量
                kafkaConsumer.commitAsync(new OffsetCommitCallback() {
                    @Override
                    public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception e) {
                        if(e!=null){
                            System.out.println("记录错误的提交偏移量："+ offsets+",异常信息"+e);
                        }
                    }
                });
            }
        }

    }
}
